package fr.expdev.bndd.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import fr.expdev.bndd.Main;

import android.os.AsyncTask;
import android.util.Log;

public class PostsAsyncTask extends AsyncTask<String, Object, Object>  {
	
	private static final String TAG = "PostsAsyncTask";
	
	private Main main;
	
	private List<Post> posts = new ArrayList<Post>();

	public PostsAsyncTask(Main main) {
		super();
		this.main = main;
	}

	@Override
	protected Object doInBackground(String... pages) {
		
		
		HttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(pages[0]);
		//ResponseHandler<String> handler = new BasicResponseHandler();
		
		try {
			//_response = client.execute(method, handler);
			HttpResponse httpReponse = client.execute(method);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder bd = dbf.newDocumentBuilder();
			Document doc = bd.parse(httpReponse.getEntity().getContent());
			
			NodeList list = doc.getElementsByTagName("item");
			for(int i = 0; i < list.getLength(); i++) {
				Node item = list.item(i);
				NodeList valuesList = item.getChildNodes();
				Post post = new Post();
				
				for(int j=0; j < valuesList.getLength(); j++) {
					Node value = valuesList.item(j);
					if (value.getNodeName().equals("title")) {
						post.setTitle(readInnerNode(value));
						
					} else if (value.getNodeName().equals("description")) {
						post.setExcerpt(readInnerNode(value));
						
					} else if (value.getNodeName().equals("link")) {
						post.setLink(readInnerNode(value));
						
					} else if (value.getNodeName().equals("pubDate")) {
						Date d = new Date(Date.parse(readInnerNode(value)));
						post.setPublicationDate(d);
						
					} else if (value.getNodeName().equals("category")) {
						if (post.getType() == Post.Type.NOTHING) {
							String category = readInnerNode(value);
							if (category.equalsIgnoreCase("Google Web Toolkit")) {
								post.setType(Post.Type.GWT);
							} else if (category.equalsIgnoreCase("Général")) {
								post.setType(Post.Type.GENERAL);
							} else if (category.equalsIgnoreCase("Smarty")) {
								post.setType(Post.Type.SMARTY);
							} else if (category.equalsIgnoreCase("Sécurité")) {
								post.setType(Post.Type.SECURITY);
							} else if (category.equalsIgnoreCase("Android")) {
								post.setType(Post.Type.ANDROID);
							} else {
								post.setType(Post.Type.NOTHING);
							}
						}
					}
				}
				
				if (post.getTitle() != null) {
					posts.add(post);
				}
			}
			
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} catch (SAXException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		this.main.notifyNewPosts(this.posts);
	}
	
	private String readInnerNode(Node node) {
		String inner = "";
		NodeList list = node.getChildNodes();
		
		for(int x=0; x<list.getLength(); x++) {
			if(list.item(x) instanceof Text) {
				Text t = (Text)list.item(x);
				inner += t.getData();
			} else if(list.item(x) instanceof EntityReference) {
				EntityReference e = (EntityReference)list.item(x);
				inner += (char)Integer.parseInt(e.getNodeName().substring(1));
			}
		}
		return inner;
	}

}
